﻿using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace Auth.Api.Helpers;

public class JwtHelper
{
    private const string SecureKey = "12345678901234567890123456789012"; // 32位密钥

    public string Generate(int id)
    {
        var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecureKey));



        var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);

        var jwtHeader = new JwtHeader(signingCredentials);


        var jwtPayload = new JwtPayload(id.ToString(), null, null, null, DateTime.Today.AddDays(1));




        var jwt = new JwtSecurityToken(jwtHeader, jwtPayload);


        var jwtHandler = new JwtSecurityTokenHandler();
        var token = jwtHandler.WriteToken(jwt);
        return token;


    }


    public JwtSecurityToken Verify(string jwtToken)
    {
        var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(jwtToken, new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecureKey)),
            ValidateIssuer = false,
            ValidateAudience = false,
            ClockSkew = TimeSpan.Zero
        }, out SecurityToken validatedToken);

        var jwtSecurityToken = validatedToken as JwtSecurityToken;

        return jwtSecurityToken;
    }

}